package com.tanhua.admin.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.Movement;
import com.tanhua.model.domain.Video;
import com.tanhua.model.domain.mysql.UserInfo;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lxb哦吼吼
 * @version 1.0
 * @description: TODO
 * @date 2021/11/23 21:00
 */

@Service
public class ManageService {

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    public PageResult findAllUsers(Integer page, Integer pagesize) {
        //1、调用API分页查询数据列表   Ipage<UserInfo>
        IPage<UserInfo> iPage = userInfoApi.findAll(page, pagesize);
        List<UserInfo> records = iPage.getRecords();
        for (UserInfo record : records) {
            String key = Constants.FREEZE_USER + record.getId();
            Boolean aBoolean = redisTemplate.hasKey(key);
            if (aBoolean) {
                record.setUserStatus("2");
            }
        }
        //2、需要将Ipage转化为PageResult
        PageResult result = new PageResult(page, pagesize, (int) iPage.getTotal(), records);
        //3、构造返回值
        return result;
    }

    public UserInfo findById(Long userId) {
        UserInfo info = userInfoApi.findById(userId);
        String key = Constants.FREEZE_USER + userId;
        Boolean aBoolean = redisTemplate.hasKey(key);
        if (aBoolean) {
            info.setUserStatus("2");
        }
        return info;
    }

    public PageResult findAllVideos(Integer page, Integer pagesize, Long userId) {
        //1、调用API查询视频列表（PageResult<video>）
        List<Video> items = videoApi.findAll(page, pagesize, userId);
        //2、获取到分页对象中的List List<Video>
        UserInfo info = userInfoApi.findById(userId);
        //3、一个Video转化成一个VideoVo
        List<VideoVo> list = new ArrayList<>();
        for (Video item : items) {
            VideoVo vo = VideoVo.init(info, item);
            list.add(vo);
        }
        //4、构造返回
        return new PageResult(page, pagesize, 0, list);
    }

    public PageResult findAllMovements(Integer page, Integer pagesize, Long userId, String state) {
        //1、调用API查询 ：（PageResult<Publish>）
        PageResult result = movementApi.findByUserId(userId, page, pagesize, state == null ? null : Integer.valueOf(state));
        //2、一个Publsh构造一个Movements
        List<Movement> items = (List<Movement>) result.getItems();
        List<MovementsVo> list = new ArrayList<>();
        for (Movement item : items) {
            UserInfo userInfo = userInfoApi.findById(item.getUserId());
            MovementsVo vo = MovementsVo.init(userInfo, item);
            list.add(vo);
        }
        //3、构造返回值
        result.setItems(list);
        return result;
    }

    public Map userFreeze(Map params) {
        Long userId = (Long) params.get("userId");
        Integer day = (Integer) params.get("freezingTime");
        day = day == 1 ? 3 : (day == 2 ? 7 : -1);
        String value = JSON.toJSONString(params);
        redisTemplate.opsForValue().set(Constants.FREEZE_USER + userId, value);
        if (day > 0) {
            redisTemplate.expire(Constants.FREEZE_USER + userId, Duration.ofMinutes(day));
        }
        Map map = new HashMap(1);
        map.put("message", "冻结成功");
        return map;
    }

    public Map userUnfreeze(Map params) {
        Long userId = (Long) params.get("userId");
        String reasonsForThawing = (String) params.get("reasonsForThawing");
        redisTemplate.delete(Constants.FREEZE_USER + userId);
        Map map = new HashMap(1);
        map.put("message", "解冻成功");
        return map;
    }
}
